﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using PhoneBook.Core.Domain.Contacts;
using PhoneBook.Core.Domain.Phones;
using PhoneBook.Extensions;
using PhoneBook.Models.Contacts;
using PhoneBook.Models.Phones;
using PhoneBook.Models.UserGroups;
using PhoneBook.Service.Contacts;
using PhoneBook.Service.UserGroups;

namespace PhoneBook.Controllers
{
    public class ContactController : Controller
    {
        private IContactService _contactService;
        private IUserGroupService _userGroupService;

        public ContactController(IContactService contactService, IUserGroupService userGroupService)
        {
            _contactService = contactService;
            _userGroupService = userGroupService;
        }

        public ActionResult SearchContact(ContactSearchFilterModel searchFilter)
        {

            var contactList = new List<ContactListModel>();

            if (searchFilter == null)
            {
                contactList = null;
            }
            else
            {

                var filter = new ContactSearchFilter()
                                 {

                                     ContactName = searchFilter.ContactName,
                                     GroupName = searchFilter.GroupName
                                 };
                var result = _contactService.SearchContact(filter);

                if(result != null)
                {
                    contactList = result.Select(c => c.ToListModel()).ToList();
                }
            }

            return View("SearchContact", contactList);

        }

        public ActionResult Index()
        {
            var contacts = _contactService.GetAllContacts();

            var contactList = contacts.Select(c => c.ToListModel()).ToList();
            return View("ContactList", contactList);
        }

        public JsonResult Delete(int contactId)
        {
            try
            {
                _contactService.DeleteContact(contactId);

                return Json(new { Status = "success" });
            }
            catch(Exception e)
            {
                return Json(new { Status = "failed" });
            }

        }

        public ActionResult Edit(int contactId)
        {
            var c = _contactService.GetContact(contactId);

            var allUserGroups = _userGroupService.GetAllUserGroups();


            var allUserGroupModel = allUserGroups.Select(t => t.ToAddOrEditModel()).ToList();
            allUserGroupModel.Where(u => c.UserGroups.Select(g => g.Id).Contains(u.GroupId)).ToList().ForEach(ag => ag.Checked = true);
      

            var model = c.ToAddOrEditModel();
            model.UserGroups = allUserGroupModel;
            if(model.Phones==null || model.Phones.Count==0)
            {
                model.Phones = new List<PhoneAddOrEditModel>()
                                   {
                                       new PhoneAddOrEditModel()
                                           {
                                               SelectedPhoneType = "Mobile",
                                               PhoneNumber = "",
                                           }
                                   };
            }
            return View("AddOrEdit", model);
        }


        public ActionResult AddContact()
        {
            var allUserGroups = _userGroupService.GetAllUserGroups();
            var allUserGroupModel = allUserGroups.Select(c => c.ToAddOrEditModel()).ToList();

            var model = new ContactAddOrEditModel()
                            {
                                Phones = new List<PhoneAddOrEditModel>()
                                             {
                                                 new PhoneAddOrEditModel()
                                                     {
                                                         SelectedPhoneType = "Mobile",
                                                         PhoneNumber = "",
                                                     }
                                             },

                                UserGroups = allUserGroupModel
                            };
            ViewBag.Step = 0;
            return View("AddOrEdit", model);
        }

        [HttpPost]
        public JsonResult SaveContact(ContactAddOrEditModel model)
        {
            try
            {
                
            if (model.ContactId == 0)
            {
                var newContact = new Contact()
                                     {
                                         UserName = model.UserName,
                                         Memo = model.Memo
                                     };
                _contactService.AddContact(newContact);
                var contactId = newContact.Id;
                return Json(new { Status = "success", ContactId = contactId });
            }
            else
            {

                int id = _contactService.UpdateContact(model.ContactId, model.UserName, model.Memo, model.SelectedUserGroupIds,
                    model.Phones!=null? model.Phones.Select(c=>c.ToEntity()).ToList():null);

                var contactId = id;
                return Json(new { Status = "success", ContactId = contactId });
            }

            }
            catch(Exception e)
            {
                return Json(new { Status = "failed"});
            }
        }

       

        public ActionResult SearchUserGroup(string searchUserGroupKey)
        {
            throw new NotImplementedException();
        }



        public ActionResult ListContactsByUserGroup(int groupId)
        {
            var contacts  = _contactService.GetContactsByUserGroup(groupId);

            var contactList = contacts.Select(c => c.ToListModel());
            return View("ContactList", contactList);

        }

    }

}
